package com.wj1c.push.wechat.request.base;

import com.alibaba.fastjson.JSON;
import com.wj1c.push.wechat.response.base.Response;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author: Mr.Jiao
 * @date: 2018年09月03日
 */
public abstract class AbstractRequest<T extends Response> implements SupporRequest<T> {

    private Map<String,Object> map = new HashMap<>();

    public AbstractRequest(String url) {
        this.url = url;
    }

    private String url = null;

    @Override
    public String getRequestUrl() {
        return this.url;
    }

    protected final void set(String key, Object value){
        map.put(key, value);
    }

    @Override
    public final String getParams() {
        RequestMethod method = this.getMethod();
        String params = null;
        if(method == RequestMethod.POST){
            params = JSON.toJSONString(map);
        }else{
            Set<Map.Entry<String,Object>> entries =  map.entrySet();
            StringBuilder sb = new StringBuilder();
            entries.forEach(entry ->{
                String value = null;
                if(entry.getValue() != null){
                    value = entry.getValue().toString();
                }
                sb.append(entry.getKey()).append("=").append(value).append("&");
            });
            if(sb.toString().endsWith("&")){
                params = sb.substring(0, sb.length() - 1);
            }
        }
        return params;
    }

    @Override
    public void setAppidAndSecret(String appid, String secret) {
        if(appid != null){
            this.set("appid", appid);
        }
        if(secret != null){
            this.set("secret", secret);
        }
    }
}
